package org.september.pisces.menuframe.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.september.pisces.filestore.controller.FileStoreController;
import org.september.pisces.filestore.entity.FileStoreItem;
import org.september.pisces.filestore.service.FileStoreManager;
import org.september.pisces.menuframe.MenuFrameModule;
import org.september.pisces.menuframe.service.FrameService;
import org.september.pisces.menuframe.vo.MenuGourpItem;
import org.september.pisces.menuframe.vo.MenuTree;
import org.september.pisces.menuframe.vo.SimpleMenu;
import org.september.pisces.settings.service.PiscesSettingService;
import org.september.pisces.user.permission.entity.SystemUser;
import org.september.pisces.user.permission.utils.UserSessionHelper;
import org.september.simpleweb.auth.DefaultMethod;
import org.september.simpleweb.model.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;


@Controller
@RequestMapping(value = "/frame")
public class FrameController {
	
	@Autowired
	private FileStoreManager fileStoreManager;
	
	@Autowired
    private PiscesSettingService settingService;
	
	@Autowired
	private FrameService frameService;
	
	@DefaultMethod
	@RequestMapping("/index")
	public ModelAndView index(String group , String menu) throws Exception {
		ModelAndView mv = new ModelAndView();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		Map<String, String[]> pMap = request.getParameterMap();
		//组装其他参数
		for(String pname : pMap.keySet()) {
			if("menu".equals(pname)) {
				continue;
			}
			if("group".equals(pname)) {
				continue;
			}
			menu= menu+ "&"+pname+"="+request.getParameter(pname);
		}
		if(UserSessionHelper.getMenuTree(group)==null) {
			group = MenuFrameModule.menuTreeGroup.getGroupNames().get(0);
		}
		MenuTree mt = buildUserMenu(UserSessionHelper.getLoginUser(),group);
		UserSessionHelper.setMenuTree(group,mt);
		if(!StringUtils.hasText(menu)) {
			menu = mt.getRoot().get(0).getChildren().get(0).getUrl();
		}
		mv.addObject("menu", menu);
		mv.addObject("realName", UserSessionHelper.getLoginUser().getRealname());
		
		mv.addObject("menuGroup", group);
		mv.addObject("menuTree", UserSessionHelper.getMenuTree(group));
		mv.addObject("commonIncludeFtls", MenuFrameModule.commonIncludeFtls.get(group));
		
		mv.addObject("logoUrl",frameService.getLogoUrl());
		return mv;
	}
	
	@DefaultMethod
	@RequestMapping("/route")
	public ModelAndView route() throws Exception {
		ModelAndView mv = new ModelAndView();
		List<String> groups = MenuFrameModule.menuTreeGroup.getGroupNames();
		List<MenuGourpItem> items = new ArrayList<>();
		for(String key : groups) {
			if(checkModule(UserSessionHelper.getLoginUser() , key)==false) {
				continue;
			}
			MenuGourpItem item = new MenuGourpItem();
			item.setName(key);
			MenuTree mt = buildUserMenu(UserSessionHelper.getLoginUser(),key);
			String fisrtMenu = mt.getRoot().get(0).getChildren().get(0).getUrl();
			item.setTargetUrl(fisrtMenu);
			item.setLabelTxt(MenuFrameModule.menuTreeGroup.getMenuTree(key).getGroupLabel());
			items.add(item);
		}
		mv.addObject("items", items);
		return mv;
	}
	
	@RequestMapping("/uploadLogo")
	@ResponseBody
	public ResponseVo<String>  uploadLogo(MultipartFile file) throws Exception {
		FileStoreItem item = fileStoreManager.save(null, file.getBytes(), "png", false, 1f);
		///pisces/fileStore/getFile?uuid=4701dad9-5413-4d3b-8fee-38a448c6d083
		settingService.update("自定义logo", "logoUrl", FileStoreController.Get_File_Action+"?uuid="+item.getFileUUID(), null, null);
		return ResponseVo.<String>BUILDER().setData("success").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
	}

	private MenuTree buildUserMenu(SystemUser loginUser,String group) {
		MenuTree mt = MenuFrameModule.menuTreeGroup.getMenuTree(group).clone();
//		MenuTree mt = MenuFrameModule.menuTree.clone();
		checkMenus(mt.getRoot(),loginUser.getPermitUrlList());
		List<SimpleMenu> removed = new ArrayList<>();
		for(SimpleMenu menu : mt.getRoot()) {
			if(menu.getChildren().isEmpty()) {
				removed.add(menu);
			}
		}
		mt.getRoot().removeAll(removed);
		return mt;
	}
	
	private boolean checkModule(SystemUser loginUser , String group) {
		List<SimpleMenu> menus = MenuFrameModule.menuTreeGroup.getMenuTree(group).getRoot();
		for(SimpleMenu firstMenu : menus) {
			for(SimpleMenu secondMenu : firstMenu.getChildren()) {
				if(loginUser.getPermitUrlList().contains(secondMenu.getUrl())) {
					return true;
				}
			}
		}
		return false;
	}

	private void checkMenus(List<SimpleMenu> menus, List<String> permitUrlList) {
		if(menus.isEmpty()) {
			return;
		}
		List<SimpleMenu> removed = new ArrayList<>();
		for(SimpleMenu menu : menus) {
			if(!StringUtils.hasText(menu.getUrl())) {
				checkMenus(menu.getChildren(),permitUrlList);
				continue;
			}
			if(!permitUrlList.contains(menu.getUrl())) {
				removed.add(menu);
			}else {
				checkMenus(menu.getChildren(),permitUrlList);
			}
		}
		menus.removeAll(removed);
	}
}
